package com.xxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxy.context.BaseContext;
import com.xxy.entity.Order;
import com.xxy.entity.Product;
import com.xxy.entity.dto.OrderDTO;
import com.xxy.entity.dto.ProductQueryDTO;
import com.xxy.entity.vo.ProductVO;
import com.xxy.mapper.OrderMapper;
import com.xxy.mapper.ProductMapper;
import com.xxy.result.PageResult;
import com.xxy.result.Result;
import com.xxy.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderMapper orderMapper;


    @Override
    public void saveProduct(Product product) {
        product.setUserId(BaseContext.getCurrentId());
        product.setCreateTime(LocalDateTime.now());
        productMapper.insert(product);
    }

    @Override
    public void update(Product product) {
        this.updateById(product);
    }

    @Override
    public PageResult query(ProductQueryDTO productQueryDTO) {
        /*LambdaQueryWrapper<Product> queryWrapper=new LambdaQueryWrapper<>();
        if (productQueryDTO.getCurrent()==null || productQueryDTO.getCurrent()==0) {
            productMapper.selectList(queryWrapper);
        }*/
        Page<ProductVO> page = new Page<>(productQueryDTO.getCurrent(), productQueryDTO.getSize());

        IPage<ProductVO> resultPage = productMapper.query(page, productQueryDTO);

        // 获取查询结果数据
        List<ProductVO> records = resultPage.getRecords();
        long total = resultPage.getTotal();

        // 封装为统一分页返回对象
        return new PageResult(total, records);
    }

    @Override
    public List<ProductVO> queryByFilter(ProductQueryDTO productQueryDTO) {
        return productMapper.queryByFilter(productQueryDTO);
    }

    @Override
    public ProductVO queryById(Integer id) {
        return productMapper.queryById(id);
    }

    @Override
    public Result<String> buyProduct(OrderDTO orderDTO) {
        if (orderDTO.getProductId() == null) {
            return Result.error("商品信息异常");
        }
        ProductQueryDTO productQueryDTO = new ProductQueryDTO();
        productQueryDTO.setId(orderDTO.getProductId());
        List<ProductVO> productVOS = productMapper.queryByFilter(productQueryDTO);
        if (productVOS.isEmpty()) {
            return Result.error("商品信息异常");
        }
        //查询库存数量
        if (productVOS.get(0).getInventory() <= 0 || productVOS.get(0).getInventory() < orderDTO.getBuyNum()) {
            return Result.error("商品已售完");
        }
        ProductVO productVO = productVOS.get(0);
        Order orders = generateOrder(orderDTO, productVO);
        orderMapper.insert(orders);
        //扣库存
        productMapper.updateById(Product.builder()
                .id(productVO.getId())
                .inventory(productVO.getInventory() - orderDTO.getBuyNum())
                .build());
        return Result.success("下单成功,快去订单页支付吧");
    }

    @Override
    public Result<String> placeOrder(Long ordersId) {
        Order order = Order.builder()
                .id(ordersId)
                .tradeStatus(1)
                .tradeTime(LocalDateTime.now())
                .build();
        orderMapper.updateById(order);
        return Result.success("下单成功");
    }

    @Override
    public Result<String> refund(Long ordersId) {
        Order order = Order.builder()
                .id(ordersId)
                .refundStatus(1)
                .tradeTime(LocalDateTime.now())
                .build();
        orderMapper.updateById(order);
        return Result.success("申请退款成功,请等待卖家审核");
    }


    //生成订单
    private Order generateOrder(Order order, ProductVO productVO) {
        //设置订单号
        order.setCode(generateOrderNumber());
        //设置下单时间
        order.setCreateTime(LocalDateTime.now());
        //设置交易状态
        order.setTradeStatus(0);
        //设置购买数量
        order.setBuyNum(order.getBuyNum());
        //设置购买价格
        order.setBuyPrice(productVO.getPrice());
        //设置用户id
        order.setUserId(BaseContext.getCurrentId());
        return order;
    }

    //生成订单号
    private String generateOrderNumber() {
        //根据时间戳设置订单号
        return String.valueOf(System.currentTimeMillis());
    }


}
